import config from "@/request/config.js";
import local from '@/utils/localStorage.js'; //引入本地存储方法
const BASE_URL = config.serveURL; //公共请求头
/**
 * 计算时间多久前
 */
export const friendlyFormatTime = function(stringTime) {
	let str = stringTime;
	//将字符串转换成时间格式
	let timePublish = new Date(str);
	let timeNow = new Date();
	let minute = 1000 * 60;
	let hour = minute * 60;
	let day = hour * 24;
	let month = day * 30;
	let year = month * 12;
	let diffValue = timeNow - timePublish;
	let diffMonth = diffValue / month;
	let diffWeek = diffValue / (7 * day);
	let diffDay = diffValue / day;
	let diffHour = diffValue / hour;
	let diffMinute = diffValue / minute;
	let diffYear = diffValue / year;
	let result = null
	if (diffValue < 0) {
		result = "刚刚";
	} else if (diffYear > 1) {
		result = parseInt(diffYear) + "年前";
	} else if (diffMonth > 1) {
		result = parseInt(diffMonth) + "月前";
	} else if (diffWeek > 1) {
		result = parseInt(diffWeek) + "周前";
	} else if (diffDay > 1) {
		result = parseInt(diffDay) + "天前";
	} else if (diffHour > 1) {
		result = parseInt(diffHour) + "小时前";
	} else if (diffMinute > 1) {
		result = parseInt(diffMinute) + "分钟前";
	} else {
		result = "刚刚";
	}
	return result;
};

/**
 * 日期转换
 */
export const timestampToDate = function(number, format = "Y-m-d H:i:s") {
	let date
	if (typeof(number) == 'object') {
		date = number

	} else {
		date = new Date(number)
	}
	let year = date.getFullYear()
	let month = date.getMonth() + 1
	let dates = date.getDate()
	let hours = date.getHours()
	let minutes = date.getMinutes()
	let seconds = date.getSeconds()
	let str = format
	if (str.indexOf("Y") != -1) {
		str = str.replace("Y", year)
	}
	if (str.indexOf("m") != -1) {
		str = str.replace("m", preposeZero(month))
	}
	if (str.indexOf("d") != -1) {
		str = str.replace("d", preposeZero(dates))
	}
	if (str.indexOf("H") != -1) {
		str = str.replace("H", preposeZero(hours))
	}
	if (str.indexOf("i") != -1) {
		str = str.replace("i", preposeZero(minutes))
	}
	if (str.indexOf("s") != -1) {
		str = str.replace("s", preposeZero(seconds))
	}
	return str
};

// 前置补0
export const preposeZero = function(number) {
	return number < 10 ? ("0" + number) : number
};

export const imgaeUrl = function(url) {
	let URL = BASE_URL + url;
	return URL
};
/**
 * 支付
 *  @param {Object} data 支付的参数
 *  @param {Object}payType 支付类型
 *  @param {Object}type 小程序  app  支付  区分
 */
export const payment = function(data, type = 'applet', payType = 'wxpay') {
	console.log(data, payType, type);
	return new Promise(async (resolve, reject) => {
		if (type == 'applet') {
			uni.requestPayment({
				provider: payType,
				...data,
				complete(ret) {
					return resolve(ret)
				},
			})
		} else {
			uni.requestPayment({
				provider: payType,
				orderInfo: data,
				complete(ret) {
					return resolve(ret)
				},
			})
		}
	})
};
/**
 * 页面跳转
 * 
 * @param {Object} url跳转路径
 * @param {Object} name 监听的名字
 * @param {Object} parameter 参数
 */
export const navigateTo = function(url, name, parameter) {
	uni.navigateTo({
		url,
		success: (res) => {
			res.eventChannel.emit(name, parameter)
		}
	})
};
/**
 * 页面跳转
 * 
 * @param {Object} url跳转路径
 * @param {Object} name 监听的名字
 * @param {Object} parameter 参数
 */
export const switchTab = function(url) {
	uni.switchTab({
		url,

	})
};
/**
 * 返回
 */
export const navigateBack = function(time) {
	console.log(time);
	setTimeout(() => {
		uni.navigateBack()
	}, time)
};
/**
 * @param {Object} url跳转路径
 * 关闭当前页面
 */
export const redirectTo = function(url) {
	uni.redirectTo({
		url,
	})
};
/**
 * @param {Object} url跳转路径
 * 关闭所有页面，打开到应用内的某个页面。
 */
export const reLaunch = function(url) {
	uni.reLaunch({
		url,
	})
};
/**
 * @param {Object} current
 * @param {Object} urls  预览图片
 */
export const previewImage = function(current, urls) {
	console.log(current, urls);
	uni.previewImage({
		current,
		urls
	})
};
/**
 * 视频封面第一帧
 * @param {Object} url 视频路径
 */
export const getVideoBase64 = function(url) {
	let dataURL = '';
	let video = document.createElement("video");
	video.setAttribute('crossOrigin', 'anonymous'); //处理跨域
	video.setAttribute('src', url);
	video.setAttribute('width', 400);
	video.setAttribute('height', 240);
	video.setAttribute('autoplay', 'autoplay');
	video.addEventListener('canplaythrough', function() {
		let canvas = document.createElement("canvas"),
			width = video.width, //canvas的尺寸和图片一样
			height = video.height;
		canvas.width = width;
		canvas.height = height;
		canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
		dataURL = canvas.toDataURL('image/jpeg'); //转换为base64
		return dataURL
	})
};
/**
 * 获取图片大小
 * @param {Object} url 图片路径
 */
export const getImageInfo = function(url) {
	uni.getImageInfo({
		src: url,
		success: function(ret) {
			console.log(ret);
			return ret.width;
		}
	})
};
/**
 * 获取页面路径
 */
export const signLink = function() {
	if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
		window.entryUrl = document.location.href
	}
	return /(Android)/i.test(navigator.userAgent) ? document.location.href : window.entryUrl;
};

/**
 * 提示框
 */
export const nativeUI = function(masg) {
	// #ifdef APP
	plus.nativeUI.toast(masg)
	// #endif
	// #ifdef H5 ||   MP-WEIXIN
	uni.$uv.toast(masg);
	// #endif
};
/**
 * 复制  剪切板
 *  @param {Object} text 复制的 文字
 */
export const setClipboardData = function(text) {
	console.log(text);
	uni.setClipboardData({
		data: text + '',
		success: res => {
			console.log(res);
			uni.getClipboardData({
				success: res => {
					console.log(res)
					uni.showToast({
						title: '复制成功'
					})
				}
			});
		},
	});
};
/**
 * 保存图片
 */
// 保存图片
export const SavePicture = function(img) {
	uni.downloadFile({
		url: img,
		success: (res) => {
			if (res.statusCode === 200) {
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success: function() {
						uni.showToast({
							title: "保存成功",
							icon: "none"
						});
					},
					fail: function() {
						uni.showToast({
							title: "保存失败，请稍后重试",
							icon: "none"
						});
					}
				});
			}
		}
	});
};
/**
 *  @param {Object} text 钻换的 文字
 */
export const parse = function(text) {
	return JSON.parse(text)
};


/**
 * @param {Object} fun 函数
 * @param {Object} delay  时间  防抖
 * import debounce from "../utils/debounce";
import throttle from "../utils/throttle";

export default {
methods: {
// 使用防抖处理的方法
handleInput: debounce(function() {
// 输入处理逻辑
}, 500),

// 使用节流处理的方法
handleScroll: throttle(function() {
// 滚动处理逻辑
}, 1000)
}
}
 */
export function debounce(fn, delay) {
	let timer = null;
	return function() {
		let context = this;
		let args = arguments;
		clearTimeout(timer);
		timer = setTimeout(function() {
			fn.apply(context, args);
		}, delay);
	};
}
/**
 * @param {Object} fun 函数
 * @param {Object} delay  时间  节流
 */
export function throttle(fn, interval) {
	let lastTime = 0;
	return function() {
		let now = Date.now();
		if (now - lastTime >= interval) {
			lastTime = now;
			fn.apply(this, arguments);
		}
	};
}
/**
 * 分享
 */

export const share = function(provider = 'weixin', scene, href, title, summary, imageUrl) {
	console.log(provider = 'weixin', scene, href, title, summary, imageUrl);
	uni.share({
		provider, //分享地方
		scene, //类型
		type: 0,
		href, //地址
		title, //名称
		summary, //描述
		imageUrl, //封面
		success: function(res) {
			console.log("success:" + JSON.stringify(res));
			nativeUI('分享成功！');
		},
		fail: function(err) {
			console.log("fail:" + JSON.stringify(err));
			nativeUI('分享失败！');
		}
	});
};
// 隐藏手机号中间四位
export const phoneFilter = function(val) {
	let reg = /^(.{3}).*(.{4})$/;
	return val.toString().replace(reg, '$1****$2');
}

// 保存页面失效当前路径
export const saveClosePage = function(val) {
	const pages = getCurrentPages(); // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面
	// 获取到当前页面的路径和参数
	const page = pages[pages.length - 1].$page.fullPath; //完整路由地址
	local.set('losePageUrl', page)
	// // 防止多个接口401跳转多次页面
	local.set('isLoseLogin', true)
}
// 退出记录当前页面路径登录并跳转
export const losePageUrl = function(val) {
	let url = local.get('losePageUrl')
	if (url == '/subcontracting/Login/login/login') {
		uni.switchTab({
			url: '/pages/Home/home/home'
		})
		return
	}
	if (url) {
		uni.redirectTo({
			url,
			success: (s) => {
				// 防止多个接口401跳转多次页面
				local.set('losePageUrl', '')
				// // 防止多个接口401跳转多次页面
				local.set('isLoseLogin', false)
			},
			fail: (f) => {
				uni.switchTab({
					url,
				})
				// 防止多个接口401跳转多次页面
				local.set('losePageUrl', '')
				// // 防止多个接口401跳转多次页面
				local.set('isLoseLogin', false)
			}
		})
	} else {
		uni.switchTab({
			url: '/pages/Home/home/home'
		})
		local.set('losePageUrl', '')
		local.set('isLoseLogin', false)
	}
}
// isGetCode false检测是否注册过 true获取code
export const wxLoginCode = function() {
	return new Promise(async (resolve, reject) => {
		uni.login({
			success: async (res) => {
				resolve(res)
			}
		})
	})
}
/**
 * @param {Object} 手机号隐藏中间4为
 */
export const geTel = function(tel) {
	console.log(tel);
	if (!tel) return
	return tel.substring(0, 3) + "****" + tel.substr(tel.length - 4);
}
// 拨打电话
export const makePhoneCall = function(phone) {
	uni.makePhoneCall({
		phoneNumber: phone //仅为示例
	});
}